package com.igoal.dao.interceptor;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

import com.igoal.entity.Audit;

/**
 * Update timestamp
 * @author tri
 *
 */
public class AuditInterceptor extends EmptyInterceptor {

	private static final long serialVersionUID = 1672109693084610621L;
	
	@Override
	public boolean onSave(Object entity, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) {
		if(entity instanceof Audit){
//			setValue(state, propertyNames, "createDate", new Date());
//			setValue(state, propertyNames, "updateDate", new Date());
		}
		
		return true;
	}
	
	@Override
	public boolean onFlushDirty(Object entity, Serializable id,
			Object[] currentState, Object[] previousState,
			String[] propertyNames, Type[] types) {
		if(entity instanceof Audit){
			setValue(previousState, propertyNames, "updateDate", new Date());
		}
		
		return true;
	}

	private void setValue(Object[] currentState, String[] propertyNames,
             String propertyToSet, Object value) {
		List<String> propNames = Arrays.asList(propertyNames);
		int index = propNames.indexOf(propertyToSet);
		if(index >=0 ){
			currentState[index] = value;
		}
		
	}
}
